<template>
	<view class="login-container">
		<!-- 渐变背景 -->
		<view class="gradient-bg"></view>
		
		<!-- 登录卡片 -->
		<view class="login-card">
			<!-- 标题区域 -->
			<view class="title-section">
				<text class="welcome-title">欢迎回来</text>
				<text class="welcome-subtitle">请登录您的账号</text>
			</view>
			
			<!-- 表单区域 -->
			<view class="form-section">
				<!-- 用户名输入框 -->
				<view class="input-group">
					<u-input 
						v-model="form.phone"
						placeholder="请输入手机号或用户名"
						prefix-icon="account"
						prefix-icon-style="color: #a6c0fe"
						type="text"
						border="surround"
						custom-style="background: #f8f9fa; border-radius: 20rpx; height: 100rpx;"
					></u-input>
				</view>
				
				<!-- 密码输入框 -->
				<view class="input-group">
					<u-input 
						v-model="form.password"
						placeholder="请输入密码"
						prefix-icon="lock"
						prefix-icon-style="color: #a6c0fe"
						:type="showPassword ? 'text' : 'password'"
						:suffix-icon="showPassword ? 'eye-off' : 'eye'"
						suffix-icon-style="color: #999"
						@suffix-icon-click="togglePasswordVisibility"
						border="surround"
						custom-style="background: #f8f9fa; border-radius: 20rpx; height: 100rpx;"
					></u-input>
				</view>
				
				<!-- 记住我和忘记密码 -->
				<view class="options-row">
					<view class="remember-me" @click="toggleRemember">
						<view class="checkbox" :class="{ 'checked': rememberMe }">
							<text v-if="rememberMe" class="checkmark">✓</text>
						</view>
						<text class="remember-text">记住我</text>
					</view>
					<text class="forgot-password" @click="forgetPassWord">忘记密码？</text>
				</view>
				
				<!-- 登录按钮 -->
				<view class="login-btn" @click="login">
					<text class="login-btn-text">登录</text>
				</view>
				
				<!-- 注册链接 -->
				<view class="register-section">
					<text class="register-text">还没有账号？</text>
					<text class="register-link" @click="register">立即注册</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import storage from '@/utils/storage.js'

export default {
	data() {
		return {
			form: {
				phone: '',
				password: '',
			},
			loginAttempts: 0,
			maxAttempts: 5,
			rememberMe: false,
			showPassword: false,
			rules: {
				phone: [
					{ 
						required: true, 
						message: '请输入帐号', 
						trigger: ['change','blur'],
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码', 
						trigger: ['change','blur'],
					}
				]
			}
		};
	},
	methods: {
		toggleRemember() {
			this.rememberMe = !this.rememberMe;
		},
		togglePasswordVisibility() {
			this.showPassword = !this.showPassword;
		},
		async login() {
			if (!this.form.phone.trim()) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return;
			}
			
			if (!this.form.password.trim()) {
				uni.showToast({
					title: '请输入密码',
					icon: 'none'
				});
				return;
			}
			
			// 检查登录保护设置
			await this.checkLoginProtection();
			
			// 调用本地存储登录
			const result = storage.login(this.form.phone, this.form.password);
			
			if (result.success) {
				// 重置登录尝试次数
				this.loginAttempts = 0;
				uni.removeStorageSync('loginLockTime');
				
				// 记录成功登录日志
				this.recordLoginLog(true);
				
				// 记住账号
				if (this.rememberMe) {
					uni.setStorageSync('rememberedAccount', this.form.phone);
				} else {
					uni.removeStorageSync('rememberedAccount');
				}
				
				// 直接跳转，避免toast卡住
				uni.switchTab({
					url: '/pages/index/index'
				});
			} else {
				// 记录失败登录日志
				this.recordLoginLog(false);
				
				// 增加登录失败次数
				this.loginAttempts++;
				
				// 检查是否需要锁定
				if (this.loginAttempts >= this.maxAttempts) {
					const lockTime = Date.now() + (30 * 60 * 1000); // 锁定30分钟
					uni.setStorageSync('loginLockTime', lockTime);
					
					uni.showModal({
						title: '账号已锁定',
						content: '连续登录失败次数过多，账号已被锁定30分钟',
						showCancel: false
					});
					return;
				}
				
				let message = result.message;
				if (this.loginAttempts >= this.maxAttempts - 2) {
					message += `（还有${this.maxAttempts - this.loginAttempts}次机会）`;
				}
				
				uni.showToast({
					title: message,
					icon: 'none'
				});
			}
		},
		register(){
			uni.navigateTo({
				url: '/pages/public/register'
			});
		},
		forgetPassWord(){
			uni.navigateTo({
				url: '/pages/public/forget_password'
			});
		},
		// 检查登录保护
		async checkLoginProtection() {
			// 检查登录限制
			const loginLimit = uni.getStorageSync('loginLimit');
			if (loginLimit) {
				const lockTime = uni.getStorageSync('loginLockTime');
				if (lockTime && Date.now() < lockTime) {
					const remainingTime = Math.ceil((lockTime - Date.now()) / (60 * 1000));
					uni.showModal({
						title: '账号已锁定',
						content: `账号已被锁定，还剩${remainingTime}分钟解锁`,
						showCancel: false
					});
					throw new Error('账号已锁定');
				}
			}
			
			// 检查异常登录检测
			const anomalyDetection = uni.getStorageSync('anomalyDetection');
			if (anomalyDetection) {
				const now = new Date();
				const hour = now.getHours();
				
				// 检查是否在异常时间段（凌晨2-6点）
				if (hour >= 2 && hour <= 6) {
					const confirm = await this.showConfirm(
						'异常时间登录',
						'检测到您在凌晨时间段登录，是否继续？'
					);
					if (!confirm) {
						throw new Error('用户取消登录');
					}
				}
			}
		},
		
		// 记录登录日志
		recordLoginLog(success = true) {
			const systemInfo = uni.getSystemInfoSync();
			const log = {
				time: new Date().toLocaleString(),
				device: `${systemInfo.model} (${systemInfo.platform})`,
				status: success ? 'success' : 'failure',
				statusText: success ? '成功' : '失败',
				phone: this.form.phone
			};
			
			let history = uni.getStorageSync('loginHistory') || [];
			history.push(log);
			
			// 只保留最近50条记录
			if (history.length > 50) {
				history = history.slice(-50);
			}
			
			uni.setStorageSync('loginHistory', history);
		},
		
		// 显示确认对话框
		showConfirm(title, content) {
			return new Promise((resolve) => {
				uni.showModal({
					title,
					content,
					success: (res) => {
						resolve(res.confirm);
					}
				});
			});
		}
	},
	onLoad() {
		// 如果有记住的账号，自动填入
		const rememberedAccount = uni.getStorageSync('rememberedAccount');
		if (rememberedAccount) {
			this.form.phone = rememberedAccount;
			this.rememberMe = true;
		}
		
		// 检查是否已经登录
		if (storage.isLoggedIn()) {
			uni.switchTab({
				url: '/pages/index/index'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.login-container {
	width: 100%;
	height: 100vh;
	position: relative;
	overflow: hidden;
}

.gradient-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
	z-index: 0;
}

.login-card {
	position: relative;
	z-index: 1;
	margin-top: 200rpx;
	margin-left: 60rpx;
	margin-right: 60rpx;
	background: rgba(255, 255, 255, 0.95);
	border-radius: 40rpx;
	padding: 80rpx 60rpx;
	box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
}

.title-section {
	text-align: center;
	margin-bottom: 80rpx;
}

.welcome-title {
	display: block;
	font-size: 56rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.welcome-subtitle {
	display: block;
	font-size: 28rpx;
	color: #666;
}

.form-section {
	width: 100%;
}

.input-group {
	margin-bottom: 40rpx;
}

.input-wrapper {
	position: relative;
	background: #f8f9fa;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	height: 100rpx;
	border: 2rpx solid #e9ecef;
	transition: all 0.3s ease;
}

.input-wrapper:focus-within {
	border-color: #a6c0fe;
	background: rgba(166, 192, 254, 0.1);
}

.input-icon {
	margin-right: 20rpx;
	font-size: 36rpx;
}

.password-icon {
	font-size: 32rpx;
	cursor: pointer;
}

.input-field {
	flex: 1;
	height: 100%;
	font-size: 32rpx;
	color: #333;
	background: transparent;
	border: none;
}

.options-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 50rpx;
}

.remember-me {
	display: flex;
	align-items: center;
}

.checkbox {
	width: 32rpx;
	height: 32rpx;
	border: 2rpx solid #a6c0fe;
	border-radius: 6rpx;
	margin-right: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
}

.checkbox.checked {
	background: #a6c0fe;
	border-color: #a6c0fe;
}

.checkmark {
	color: white;
	font-size: 20rpx;
	font-weight: bold;
}

.remember-text {
	font-size: 28rpx;
	color: #666;
}

.forgot-password {
	font-size: 28rpx;
	color: #a6c0fe;
}

.login-btn {
	width: 100%;
	height: 100rpx;
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 40rpx;
	box-shadow: 0 10rpx 30rpx rgba(166, 192, 254, 0.4);
	transition: all 0.3s ease;
}

.login-btn:active {
	transform: translateY(2rpx);
	box-shadow: 0 5rpx 15rpx rgba(166, 192, 254, 0.4);
}

.login-btn-text {
	color: white;
	font-size: 36rpx;
	font-weight: bold;
}

.register-section {
	text-align: center;
}

.register-text {
	font-size: 28rpx;
	color: #666;
	margin-right: 10rpx;
}

.register-link {
	font-size: 28rpx;
	color: #a6c0fe;
	font-weight: bold;
}
</style>